import { reverseGeocoder } from '@/utils/mapUtils';

const state = {
    latitude: null,
    longitude: null,
    address: '',
    isLoading: false
  }
  
  const mutations = {
    SET_LOCATION(state, { latitude, longitude }) {
      state.latitude = latitude
      state.longitude = longitude
    },
    SET_ADDRESS(state, address) {
      state.address = address
    },
    SET_LOADING(state, status) {
      state.isLoading = status
    }
  }
  
  const actions = {
    // 获取当前位置并解析地址
    async getLocation({ commit }) {
      commit('SET_LOADING', true)
      try {
        // 1. 获取经纬度
        const res = await uni.getLocation({
          type: 'gcj02',
          altitude: true
        })
  
        commit('SET_LOCATION', {
          latitude: res.latitude,
          longitude: res.longitude
        })
  
        // 2. 调用逆地理编码API
        const addressInfo = await this.dispatch('location/reverseGeocoder', {
          latitude: res.latitude,
          longitude: res.longitude
        })
  
        commit('SET_ADDRESS', addressInfo.address)
        return addressInfo.address
  
      } catch (err) {
        console.error('获取位置失败:', err)
        uni.showToast({
          title: '无法获取位置，请检查设置',
          icon: 'none'
        })
        throw err
      } finally {
        commit('SET_LOADING', false)
      }
    },
  
    // 逆地理编码方法 - 使用统一的mapUtils
    async reverseGeocoder(_, { latitude, longitude }) {
      try {
        // 使用后端API方式
        const data = await reverseGeocoder(latitude, longitude, true);
        return data;
      } catch (error) {
        throw new Error(error.message || '地理编码失败');
      }
    }
  }
  
  const getters = {
    hasLocation: state => !!state.latitude && !!state.longitude,
    locationInfo: state => ({...state})
  }
  
  export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
  }